<template>
  <el-select v-model:value="shopId" show-search allowClear
            @change="onChange" placeholder="选择商家" clearable
  >
    <el-option v-for="item in shops" :key="item.id" :value="item.name"
                     :label="item.id + ' | ' + item.name">
      {{ item.id }} | {{ item.name }}
    </el-option>
  </el-select>
</template>

<script>

import {defineComponent, onMounted, ref, watch} from 'vue';
import axios from "axios";
import Tool from "../utils/tool";



export default defineComponent({
  name: "shop-select-view",
  props: ["modelValue"],
  emits: ['update:modelValue', 'change'],
  setup(props, {emit}) {
    const shopId = ref();
    const shops = ref([]);

    // 利用watch，动态获取父组件的值，如果放在onMounted或其它方法里，则只有第一次有效
    watch(() => props.modelValue, () => {
      console.log("props.modelValue", props.modelValue);
      shopId.value = props.modelValue;
    }, {immediate: true});


    const queryAllTrain = () => {
      const param = {
        shopIdList: []
      }
      axios.post(
          "/rest/admin/shop/list",
          param,
          {
            headers: {
              'Content-Type': 'application/json',
            }
          }
      ).then((response) => {
        let data = response.data
        console.log(data)
        if (data.success) {
          shops.value = data.data.records
        }
      });
    };


    /**
     * 将当前组件的值响应给父组件
     * @param value
     */
    const onChange = (value) => {
      emit('update:modelValue', value);
      let shop = shops.value.filter(item => item.name === value)[0];
      if (Tool.isEmpty(shop)) {
        shop = {};
      }
      emit('change', shop);
    };

    onMounted(() => {
      queryAllTrain();
    });

    return {
      shopId,
      shops,
      onChange
    };
  },
});
</script>
